package spring.module.zipfilter;

import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;

import javax.servlet.ReadListener;
import javax.servlet.ServletInputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;

import lombok.extern.slf4j.Slf4j;

/**
 * 请求包装器，判断请求数据是否压缩，如果是侧解压
 *  
 * @author Lucky Yang
 */
@Slf4j
public class UnZIPRequestWrapper extends HttpServletRequestWrapper {
    private final byte[] requestData;

    public UnZIPRequestWrapper(HttpServletRequest request) {
        super(request);
        try(BufferedInputStream bis = new BufferedInputStream(request.getInputStream());
            ByteArrayOutputStream baos = new ByteArrayOutputStream()) {
                byte[] buffer = new byte[1024];
                int len;
                while((len = bis.read(buffer)) > 0) {
                    baos.write(buffer, 0 , len);
                }

                final byte[] body = baos.toByteArray();
                if (body.length == 0) {
                    log.info("Body无内容，无需解压");
                    requestData = body;
                } else {
                    requestData = GZIPUtils.uncompress(body);
                }
            } catch (IOException ex) {
                log.info("解压缩步骤发生异常！");
                ex.printStackTrace();
                throw new ZipException(ex);      
            }
    }

    @Override
    public ServletInputStream getInputStream() throws IOException {
        final ByteArrayInputStream bais = new ByteArrayInputStream(requestData);
        return new ServletInputStream() {

            @Override
            public boolean isFinished() {
                return false;
            }

            @Override
            public boolean isReady() {
                return false;
            }

            @Override
            public void setReadListener(ReadListener listener) {     
                // 不需要实现          
            }

            @Override
            public int read() throws IOException {
                return bais.read();
            }
            
        };
    }

    @Override
    public BufferedReader getReader() throws IOException {
        return new BufferedReader(new InputStreamReader(this.getInputStream()));
    }
   
    
}
